package com.example.share_doc.config;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.share_doc.entity.Department;
import com.example.share_doc.mapper.DepartmentMapper;
import com.example.share_doc.util.Common;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class DataInitializer implements ApplicationRunner {

    @Value("${init.name}")
    private String departmentName;

    private final DepartmentMapper departmentMapper;

    public DataInitializer(DepartmentMapper departmentMapper) {
        this.departmentMapper = departmentMapper;
    }

    @Override
    public void run(ApplicationArguments args) {
        QueryWrapper<Department> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Department::getDepartmentCode, Common.DEPARTMENT_ROOT_CODE);
        Department department = departmentMapper.selectOne(queryWrapper);
        if (department != null){
            log.info("公司[{}]初始化数据已存在", department.getDepartmentName());
        }else {
            department = new Department();
            department.setDepartmentCode(Common.DEPARTMENT_ROOT_CODE);
            department.setDepartmentName(departmentName);
            department.setDepartmentParentCode(Common.DEPARTMENT_ROOT_CODE);
            departmentMapper.insert(department);
            log.info("公司[{}]初始化完成", department.getDepartmentName());
        }
    }
}